<?php
namespace app\admin\controller;
use think\Db;
use think\facade\Request;
class Device extends Common
{
    /**
     * 闸机列表
     * URL：admin/device/brakeMachine
     * @return array|mixed
     * @throws \think\exception\DbException
     */
    public function brakeMachine(){

        if (request()->isAjax()) {

            $keyword = input('post.keyword');
            $page =input('page',1);
            $pageSize =input('limit',config('pageSize'));

            $list = Db::name('device')
                ->where('is_del',0)
                ->where('type',1)
                ->where('ip|device_name', 'like', "%" . $keyword . "%")
                ->order('create_time desc')
                ->paginate(array('list_rows'=>$pageSize,'page'=>$page))
                ->toArray();

            $week_day = ['周日','周一','周二','周三','周四','周五','周六'];

            if (! empty($list)) {
                foreach ($list['data'] as $k => $v) {
                    $str = "";
                    foreach (json_decode($v['work_time']) as $key=>$val){
                        $str.=$week_day[$val]."， ";
                    }
                    $list['data'][$k]['work_time']=$str;
                    $list['data'][$k]['create_time'] = toDate($v['create_time']);
                    $list['data'][$k]['day_time'] = $v['start_time']." ~ ".$v['end_time'];
                }

            }

            return $result = ['code'=>0,'msg'=>'成功!','data'=>$list['data'],'count'=>$list['total'],'rel'=>1];
        }

        return $this->fetch('brake_machine');
    }

    /**
     * 添加闸机设备
     * URL：admin/device/brakeMachineAdd
     * @return \think\response\View
     */
    public function brakeMachineAdd(){

        if(Request::isAjax()){
            $data = input('post.');
            $data['add_parentname']     = session('username');
            $data['create_time'] = time();
            $data['ip'] = request()->ip();
            $data['type'] = 1;
            $ret = Db::name('device')->insert($data);
            $log = [
                'content'=>'添加闸机'.$data['device_name']
            ];
            $wed = new Weblog();
            $res = $wed->insert($log);
            //添加
            if ($ret && $res) {
                $this->success('闸机添加成功',url('brakeMachine'));
            }else {
                $this->error('闸机添加失败!');
            }

        }else{

            $this->assign('title',lang('add').lang('brakeMachine'));
            $this->assign('info','null');
            return view('brake_machineForm');

        }
    }

    /**
     * 编辑闸机设备
     * URL：admin/device/brakeMachineEdit
     * @return \think\response\View
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function brakeMachineEdit(){

        if(request()->isPost()){
            $data = input('post.');
            $ret = Db::name('device')->where('id',$data['id'])->update($data);
            $log = [
                'content'=>'编辑闸机'.$data['device_name']
            ];
            $wed = new Weblog();
            $res = $wed->insert($log);
            if ($ret && $res){
                $this->success('闸机修改成功',url('brakeMachine'));
            }else{
                $this->error('闸机修改失败',url('brakeMachine'));
            }

        }else{

            $info = Db::name('device')->where('id',input('id'))->find();
            $info['work_time'] = json_decode($info['work_time'],true);
            // $this->assign('info', json_encode($info,true));
            $this->assign('info', $info);
            $this->assign('title',lang('edit').lang('brakeMachine'));
            return view('brake_machineForm');
        }
    }

    /**
     * 删除闸机设备
     * URL：admin/device/brakeMachineDel
     * @return array
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function brakeMachineDel(){
        $id=input('post.id');
        if (session('aid')==1){
            Db::name('device')->where('id', $id)->update(['is_del' => 1]);
            $device_name = Db::name('device')->where('id', $id)->value('device_name');
            $log = [
                'content'=>'删除闸机'.$device_name
            ];
            $wed = new Weblog();
            $wed->insert($log);
            $this->success('删除成功!');
            return $result = ['code'=>1,'msg'=>'删除成功!'];
        }else{
            $this->error('您没有删除闸机的权限!');
        }
    }


    /**
     * 修改闸机设备状态
     * URL：admin/device/brakeMachineState
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function brakeMachineState(){
        $id=input('post.id');
        $status=input('post.status');

        if (empty($id)){
            $this->error('该闸机不存在');
        }

        $ret  = Db::name('device')->where('id',$id)->update(['status'=>$status]);
        $res1 = Db::name('device')->where('id',$id)->value('device_name');
        $log = [
            'content'=>'修改闸机状态'.$res1
        ];
        $wed = new Weblog();
        $res = $wed->insert($log);
        if($ret && $res){
            $this->success('闸机状态修改成功');
        }else{
            $this->error('闸机状态修改失败');
        }

    }
    /**
     * ******************************************************************
     * 打卡机管理
     */

    /**
     * 打卡机列表
     * URL：admin/device/punchMachine
     * @return array|mixed
     * @throws \think\exception\DbException
     */
    public function punchMachine(){

        if (request()->isAjax()) {

            $keyword = input('post.keyword');
            $page =input('page',1);
            $pageSize =input('limit',config('pageSize'));

            $list = Db::name('device')->alias('d')
                ->join('device_screen ds','d.screen_id=ds.id')
                ->where('d.is_del',0)
                ->where('d.type',2)
                ->where('d.ip|d.device_name', 'like', "%" . $keyword . "%")
                ->field('d.*,ds.id as screen_id,ds.screen_name')
                ->order('d.create_time desc')
                ->paginate(array('list_rows'=>$pageSize,'page'=>$page))
                ->toArray();

            $week_day = ['周日','周一','周二','周三','周四','周五','周六'];

            if (!empty($list)) {
                foreach ($list['data'] as $k => $v) {
                    $str = "";
                    foreach (json_decode($v['work_time']) as $key=>$val){
                        $str.=$week_day[$val]."， ";
                    }
                    $list['data'][$k]['work_time']=$str;
                    $list['data'][$k]['create_time'] = toDate($v['create_time']);
                    $list['data'][$k]['day_time'] = $v['start_time']." ~ ".$v['end_time'];
                }

            }

            return $result = ['code'=>0,'msg'=>'成功!','data'=>$list['data'],'count'=>$list['total'],'rel'=>1];
        }

        return $this->fetch('punch_machine');
    }


    /**
     * 添加打卡机设备
     * URL：admin/device/brakeMachineAdd
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function punchMachineAdd(){

        if(Request::isAjax()){
            $data = input('post.');
            $data['add_parentname']     = session('username');
            $data['create_time'] = time();
            $data['type'] = 2;
            $ret = Db::name('device')->insert($data);
            $log = [
                'content'=>'添加打卡机'.$data['device_name']
            ];
            $wed = new Weblog();
            $res = $wed->insert($log);
            if ($ret && $res) {
                $this->success('打卡机添加成功',url('punchMachine'));
            }else {
                $this->error('打卡机添加失败!');
            }

        }else{
            $screenGroup = Db::name('device_screen')->where('is_del',0)->select();
            $this->assign('screenGroup',$screenGroup);
            $this->assign('title',lang('add').lang('punchMachine'));
            $this->assign('info','null');
            return view('punch_machineForm');

        }
    }


    /**
     * 编辑打卡机设备
     * URL：admin/device/punchMachineEdit
     * @return \think\response\View
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function punchMachineEdit(){

        if(request()->isPost()){
            $data = input('post.');
            $ret = Db::name('device')->where('id',$data['id'])->update($data);
            $log = [
                'content'=>'编辑打卡机'.$data['device_name']
            ];
            $wed = new Weblog();
            $res = $wed->insert($log);
            if ($ret && $res){
                $this->success('打卡机修改成功',url('punchMachine'));
            }else{
                $this->error('打卡机修改失败',url('punchMachine'));
            }

        }else{
            $screenGroup = Db::name('device_screen')->where('is_del',0)->select();
            $this->assign('screenGroup',$screenGroup);
            $info = Db::name('device')->where('id',input('id'))->find();
            $this->assign('info', json_encode($info,true));
            $info1 = Db::name('device')->where('id',input('id'))->find();
            $info1['work_time'] = json_decode($info1['work_time'],true);
            $this->assign('info1', $info1);
            $this->assign('title',lang('edit').lang('punchMachine'));
            return view('punch_machineForm');
        }
    }


    /**
     * 删除打卡机设备
     * URL：admin/device/punchMachineDel
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function punchMachineDel(){
        $id=input('post.id');
        if (session('aid')==1){
            $ret = Db::name('device')->where('id', $id)->update(['is_del' => 1]);
            $device_name = Db::name('device')->where('id', $id)->value('device_name');
            $log = [
                'content'=>'删除打卡机'.$device_name
            ];
            $wed = new Weblog();
            $res = $wed->insert($log);
            if ($ret && $res){
                $this->success('删除成功!');
            }else{
                $this->error('删除成功!');
            }
        }else{
            $this->error('您没有删除打卡机的权限!');
        }
    }

    /**
     * 修改打卡机设备状态
     * URL：admin/device/brakeMachineState
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function punchMachineState(){
        $id=input('post.id');
        $status=input('post.status');

        if (empty($id)){
            $this->error('该打卡机不存在');
        }

        $ret = Db::name('device')->where('id',$id)->update(['status'=>$status]);
        $res1 = Db::name('device')->where('id',$id)->value('device_name');
        $log = [
            'content'=>'修改打卡机状态'.$res1
        ];
        $wed = new Weblog();
        $res =$wed->insert($log);
        if($ret && $res){
            $this->success('打卡机状态修改成功');
        }else{
            $this->error('打卡机状态修改失败');
        }

    }


    /**
     * ******************************************************************
     * 屏显管理
     */

    /**
     * 屏显列表
     * URL：admin/device/screenMachine
     * @return array|mixed
     * @throws \think\exception\DbException
     */
    public function screenMachine(){

        if (request()->isAjax()) {

            $keyword = input('post.keyword');
            $page =input('page',1);
            $pageSize =input('limit',config('pageSize'));

            $list = Db::name('device_screen')
                ->where('is_del',0)
                ->where('ip|screen_name', 'like', "%" . $keyword . "%")
                ->order('create_time desc')
                ->paginate(array('list_rows'=>$pageSize,'page'=>$page))
                ->toArray();


            if (!empty($list)) {
                foreach ($list['data'] as $k => $v) {
                    $list['data'][$k]['create_time'] = toDate($v['create_time']);
                }

            }

            return $result = ['code'=>0,'msg'=>'成功!','data'=>$list['data'],'count'=>$list['total'],'rel'=>1];
        }

        return $this->fetch('screen_machine');
    }

    /**
     * 添加屏显设备
     * URL：admin/device/screenMachineAdd
     * @return \think\response\View
     */
    public function screenMachineAdd(){

        if(Request::isAjax()){
            $data = input('post.');
            $data['add_parentname']     = session('username');
            $data['create_time'] = time();
            $ret = Db::name('device_screen')->insert($data);
            $log = [
                'content'=>'添加屏显'.$data['screen_name']
            ];
            $wed = new Weblog();
            $res = $wed->insert($log);
            if ($ret && $res) {
                $this->success('屏显添加成功',url('screenMachine'));
            }else {
                $this->error('屏显添加失败!');
            }

        }else{

            $this->assign('title',lang('add').lang('screenMachine'));
            $this->assign('info','null');
            return view('screen_machineForm');

        }
    }


    /**
     * 编辑屏显设备
     *  URL：admin/device/screenMachineEdit
     * @return \think\response\View
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function screenMachineEdit(){

        if(request()->isPost()){
            $data = input('post.');
            $ret = Db::name('device_screen')->where('id',$data['id'])->update($data);
            $log = [
                'content'=>'编辑屏显'.$data['screen_name']
            ];
            $wed = new Weblog();
            $res = $wed->insert($log);
            if ($ret && $res){
                $this->success('屏显修改成功',url('screenMachine'));
            }else{
                $this->error('屏显修改失败',url('screenMachine'));
            }

        }else{

            $info = Db::name('device_screen')->where('id',input('id'))->find();
            $this->assign('info', json_encode($info,true));
            $info1 = Db::name('device')->where('id',input('id'))->find();
            $info1['work_time'] = json_decode($info1['work_time'],true);
            $this->assign('info1', $info1);
            $this->assign('title',lang('edit').lang('screenMachine'));
            return view('screen_machineForm');
        }
    }


    /**
     * 删除屏显设备
     * URL：admin/device/screenMachineDel
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function screenMachineDel(){
        $id=input('post.id');
        if (session('aid')==1){
            $ret = Db::name('device_screen')->where('id', $id)->update(['is_del' => 1]);
            $screen_name = Db::name('device_screen')->where('id', $id)->value('screen_name');
            $log = [
                'content'=>'删除屏显'.$screen_name
            ];
            $wed = new Weblog();
            $res = $wed->insert($log);
            if ($ret && $res){
                $this->success('删除成功!');
            }else{
                $this->error('删除成功!');
            }
        }else{
            $this->error('您没有删除屏显的权限!');
        }
    }

    /**
     * 修改屏显设备状态
     * URL：admin/device/screenMachineState
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function screenMachineState(){
        $id=input('post.id');
        $status=input('post.status');

        if (empty($id)){
            $this->error('该屏显不存在');
        }

        $ret = Db::name('device_screen')->where('id',$id)->update(['status'=>$status]);
        $res1 = Db::name('device_screen')->where('id',$id)->value('screen_name');
        $log = [
            'content'=>'修改屏显状态'.$res1
        ];
        $wed = new Weblog();
        $res =$wed->insert($log);
        if($ret && $res){
            $this->success('屏显状态修改成功');
        }else{
            $this->error('屏显状态修改失败');
        }

    }


    /**
     * 检测摄像机状态
     * @param int $device_screen_id 屏显id
     * @param int $device_id 摄像机id
     * @param int $device_status 摄像机状态
     * @param string $drop_time 上传时间
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function  device_detection($device_screen_id = 1,$device_id=4,$device_status = 0,$drop_time="1534901745"){

        //屏显正常，更改上报时间
        $res = Db::name('device_screen')->where('id',$device_screen_id)->update(['report_time'=>$drop_time]);

        //如果屏显上传的摄像机状态正常，直接返回成功
        if($device_status){

            return json([
                'code'=>200,
                'msg' =>'success'
            ]);

        }else{

            $data = [
                'drop_time'  => $drop_time,
                'online_status'  => 0
            ];

            //如果屏显上传的摄像机状态异常，更改数据库摄像机状态并更新时间
            $re = Db::name('device')->where('id',$device_id)->update($data);

            //更改状态成功，返回成功
            if($re && $res){
                return json([
                    'code'=>200,
                    'msg' =>'success'
                ]);
            }else{
                //更改状态失败，返回失败
                return json([
                    'code'=>400,
                    'msg' =>'error'
                ]);
            }

        }

    }


    /**
     * 屏显定时（10分钟）上报状态
     * URL:admin/device/report_status
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function report_status(){

        $interval = 600;
        $time_diff = time()-$interval;
        $list = Db::name('device_screen')->field('id,report_status,report_time')->select();
        foreach ($list as $k=>$v){
            if ($time_diff>$v['report_time']){
                Db::name('device_screen')->where('id',$v['id'])->update(['report_status'=>0]);
            }
        }

    }


    /**设备状态
     * URL:admin/device/statusList
     * @return array|mixed
     * @throws \think\exception\DbException
     */
    public function statusList(){

        if (request()->isAjax()) {

            $keyword = input('post.keyword');
            $page =input('page',1);
            $pageSize =input('limit',config('pageSize'));

            $list = Db::name('device_screen ds')
                ->join('device d','d.screen_id=ds.id','left')
                ->where('d.is_del',0)
                ->where('ds.screen_name|d.device_name', 'like', "%" . $keyword . "%")
                ->order('d.create_time desc')
                ->paginate(array('list_rows'=>$pageSize,'page'=>$page))
                ->toArray();

            if (! empty($list)) {
                foreach ($list['data'] as $k => $v) {

                    $list['data'][$k]['report_time'] = toDate($v['report_time']);
                    $list['data'][$k]['drop_time'] = toDate($v['drop_time']);
                }

            }

            return $result = ['code'=>0,'msg'=>'成功!','data'=>$list['data'],'count'=>$list['total'],'rel'=>1];
        }

        return $this->fetch();
    }

}